export default {
	//为当前模块开启命名空间
	namespaced: true,
	//通过state方法返回一个数据节点
	state: () => ({
		//购物车的数组，用来存储商品的信息对象
		cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
		//微信支付页面的显示
		wxzf:false
	}),

	//state中的数据只能用mutations方法修改
	mutations: {
		//向购物车添加数据
		addToCart(state, goods) {
			// 先循环cart中的每一项，相同增加数量，不同增加商品goods
			const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
			if (!findResult) {
				//如果没有查询到goods_id相同的的商品
				state.cart.push(goods)
			} else {
				findResult.goods_count++
			}
			console.log(state.cart)
			this.commit('m_cart/saveToStorage')
		},
		//将数据缓存到浏览器中
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		//更新购物车中商品的勾选状态
		updateGoodsState(state, goods) {
			const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
			if (findResult) {
				findResult.goods_state = goods.goods_state
				this.commit('m_cart/saveToStorage')
			}
		},
		//更新购物车中商品的数量
		updateGoodsCount(state, goods) {
			const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
			if (findResult) {
				findResult.goods_count = goods.goods_count
				this.commit('m_cart/saveToStorage')
			}
		},
		//删除商品，从cart数组中
		removeGoods(state, goods) {
			//通过过滤的方法filter，将ID不同的商品存储到新数组中
			state.cart = state.cart.filter(x => x.goods_id !== goods.goods_id)
			this.commit('m_cart/saveToStorage')
		},
		//全选与全不选
		updateAllstate(state,newState){
			state.cart.forEach(x => x.goods_state = newState)
			this.commit('m_cart/saveToStorage')
		},
		//改变微信支付的显示状态
		updatewxzf(state,wxzf){
			state.wxzf = wxzf
		}
	},
	//相当于vuex中的计算属性
	getters: {
		total(state) {
			// let c = 0
			// state.cart.forEach((x) => c += x.goods_count)
			// return c
			//这里的0相当于一个初始值
			return state.cart.reduce((total, item) => total += item.goods_count, 0)
		},
		//结算的总数
		checkedCount(state) {
			// filter过滤被勾选的商品
			return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
		},
		//结算的总价格
		FullPrice(state) {
			//勾选的商品的数量*价格累加到total上取2位小数
            return state.cart.filter(x => x.goods_state).reduce((total,item) => total += item.goods_count * item.goods_price,0).toFixed(2)
		}
	}
}
